<?php

/**
 * @copyright 2011
 * @version $Id$
 * @access public
 * @author oriotiori

 */

class Admin_Model_ImageHandler extends Zend_Db_Table_Abstract{

	protected $_name = 'images';

/**
 * @param mixed $form Datos provenientes del post
 * @param array $To Array de datos
 * @return int lastInsertId
 */
        public function AddCategoryFiles($form, $To)
        {

            $ruta=IMAGES_PATH.DS.$To['Directory'].DS.$To['Path'].DS;

           try{
                // Traemos el adapter de Zend_File_Transfer
                $upload = $form->category_image->getTransferAdapter();
                $i=0;

                foreach ($upload->getFileInfo() as $info)
                {
                    if(empty($info['name']))
                        break;

                    //rename file how you like and move it to given destination

                    $ext = $this->_findexts($info['name']);
                    $file = $To['Partname'].'_'.time().".".$ext;

                    $upload->addFilter('Rename',
                        array('target'=> $ruta.$file,
                            'overwrite'=>true
                        ));

                    try{
                        $subio=false;
                        $subio=$upload->receive($info['name']);
                        if($subio){
                            try{
                                $data = array('Real' => $file);
                                $res = $this->getAdapter()->insert(TABLE_PREFIX.'images', $data);
                                return $this->getAdapter()->lastInsertId();
                            }catch(Exception $e)
                            {
                                $error=array($e->getFile(), 'Exception: '.$e->getMessage());
                                $ExceptionHandler= new Default_Model_ExceptionHandler();
                                $ExceptionHandler->saveErrors($error);
                            }
                        }
                        $i++;
                    }catch( Exception $e ) {
                        $error=array($e->getFile(), 'Exception: '.$e->getMessage());
                        $ExceptionHandler= new Default_Model_ExceptionHandler();
                        $ExceptionHandler->saveErrors($error);
                    }
                }
            }catch( Exception $e ) {
                $error=array($e->getFile(), 'Exception: '.$e->getMessage());
                $ExceptionHandler= new Default_Model_ExceptionHandler();
                $ExceptionHandler->saveErrors($error);
            }
            return 0;
        }

        /**
        * @param mixed $form Datos provenientes del post
        * @param array $To Array de datos
        * @return int lastInsertId
        */
        public function AddManufacturerFiles($form, $To)
        {
        
        	$ruta=IMAGES_PATH.DS.$To['Directory'].DS.$To['Path'].DS;
        
        	try{
        		// Traemos el adapter de Zend_File_Transfer
        		$upload = $form->manufacturer_image->getTransferAdapter();
        		$i=0;
        
        		foreach ($upload->getFileInfo() as $info)
        		{
        			if(empty($info['name']))
        			break;
        
        			//rename file how you like and move it to given destination
        
        			$ext = $this->_findexts($info['name']);
        			$file = $To['Partname'].'_'.time().".".$ext;
        
        			$upload->addFilter('Rename',
        			array('target'=> $ruta.$file,
                                    'overwrite'=>true
        			));
        
        			try{
        				$subio=false;
        				$subio=$upload->receive($info['name']);
        				if($subio){
        					try{
        						$data = array('Real' => $file);
        						$res = $this->getAdapter()->insert(TABLE_PREFIX.'images', $data);
        						return $this->getAdapter()->lastInsertId();
        					}catch(Exception $e)
        					{
        						$error=array($e->getFile(), 'Exception: '.$e->getMessage());
        						$ExceptionHandler= new Default_Model_ExceptionHandler();
        						$ExceptionHandler->saveErrors($error);
        					}
        				}
        				$i++;
        			}catch( Exception $e ) {
        				$error=array($e->getFile(), 'Exception: '.$e->getMessage());
        				$ExceptionHandler= new Default_Model_ExceptionHandler();
        				$ExceptionHandler->saveErrors($error);
        			}
        		}
        	}catch( Exception $e ) {
        		$error=array($e->getFile(), 'Exception: '.$e->getMessage());
        		$ExceptionHandler= new Default_Model_ExceptionHandler();
        		$ExceptionHandler->saveErrors($error);
        	}
        	return 0;
        }
        
        
		/**
        * @param mixed $form Datos provenientes del post
        * @param array $To Array de datos
        * @return int lastInsertId
        */
        public function AddProductFiles($form, $To)
        {

        	$ruta=IMAGES_PATH.DS.$To['Directory'].DS.$To['Path'].DS;
        	$facadeProducts= new Admin_Model_Facade_Products();
        
        	try{

        		// Traemos el adapter de Zend_File_Transfer
        		$upload = $form->product_image->getTransferAdapter();
        		$i=0;
        

        		foreach ($upload->getFileInfo() as $info)
        		{
        			if(empty($info['name']))
        			continue;
        
        			//rename file how you like and move it to given destination
        
        			$ext = $this->_findexts($info['name']);
        			$file = $To['Partname'].'_'.time()."_".$i.".".$ext;
        
        			$upload->addFilter('Rename',
        					array('target'=> $ruta.$file,
                            	'overwrite'=>true
        					)
        			);
        
        			try{
        				$subio=false;
        				
        				$subio=$upload->receive($info['name']);
        				
        				if($subio){
        					try{
        						$data = array('Real' => $file);

        						$res = $this->getAdapter()->insert(TABLE_PREFIX.'images', $data);
        						$imageId= $this->getAdapter()->lastInsertId();
        						$To['IdPicture']=$imageId;
        						$imagesproduct=array(
        							"Id_Product" => $To['IdProduct'],
        							"Id_Image" => $imageId,
        						
        						);
        						$res = $this->getAdapter()->insert(TABLE_PREFIX.'images_product', $imagesproduct);
        						
        						$facadeProducts->CreateThumb($To);
				    			$facadeProducts->CreateMiniThumb($To);
				    			$facadeProducts->CreateMedium($To);
        					}catch(Exception $e)
        					{
        						$error=array($e->getFile(), 'Exception: '.$e->getMessage());
        						$ExceptionHandler= new Default_Model_ExceptionHandler();
        						$ExceptionHandler->saveErrors($error);
        					}
        				}
        				$i++;
        			}catch( Exception $e ) {
        				$error=array($e->getFile(), 'Exception: '.$e->getMessage());
        				$ExceptionHandler= new Default_Model_ExceptionHandler();
        				$ExceptionHandler->saveErrors($error);
        			}

        		}
        		if(isset($imageId))
        			return $imageId;
        		
        	}catch( Exception $e ) {
        		$error=array($e->getFile(), 'Exception: '.$e->getMessage());
        		$ExceptionHandler= new Default_Model_ExceptionHandler();
        		$ExceptionHandler->saveErrors($error);
        	}
        	return 0;
        }
   


/**
 * Método para localizar la extension de un archivo
 * @param string $filename Nombbre del archivo
 * @return string $exts Extension del archivo
 */
        protected function _findexts($filename)
        {
            $filename = strtolower($filename);
            $exts = end(explode(".", $filename)) ;
            return $exts;
        }

/**
 * Método para actualizar la informacion de images
 * @param array $to array
 * @return boolean
 */
        public function updateImages($to)
        {
            try{
                

				$data = array($to['mode'] => $to['newImage']);
                $where[]='Id='.$to['IdPicture'];
                $res = $this->getAdapter()->update(TABLE_PREFIX.'images', $data, $where);
                return $res;
                
            }catch( Exception $e ) {
                $error=array($e->getFile(), 'Exception: '.$e->getMessage());
                $ExceptionHandler= new Default_Model_ExceptionHandler();
                $ExceptionHandler->saveErrors($error);
            }
        }


/**
 * Elimina una imagen de la DB
 *  */
    public function deleteImage($id){
        $table="images";
        try{
            $where[]='Id='.$id;			
            $this->getAdapter()->delete(TABLE_PREFIX.$table ,$where);
            return true;
        }catch(Exception $e)
        {
            $error=array($e->getFile(), 'Exception: '.$e->getMessage());
            $ExceptionHandler= new Default_Model_ExceptionHandler();
            $ExceptionHandler->saveErrors($error);
        }
        return false;
    }

/**
 * Elimina una imagen real
 *  */
    public function deleteImageByPath($path){
        try{
            unlink($path);
            return true;
        }catch(Exception $e)
        {
            $error=array($e->getFile(), 'Exception: '.$e->getMessage());
            $ExceptionHandler= new Default_Model_ExceptionHandler();
            $ExceptionHandler->saveErrors($error);
        }
        return false;
    }


/**
 * Método para redimensinar una imagen
 * @param array $to array
 * @return boolean
 */
        public function CreateThumb($to)
        {
            try{
                $image_default=0;
                $image=$this->getImageById($to['IdPicture']);
                
                $image=(!$image) ?  $image_default : $image ;
                $to['newImage']=$image=(is_array($image) && $image['Real'] != '') ? $image['Real']: $image;

                $image_path=IMAGES_PATH.DS.$to['Directory'].DS.$to['Path'].DS.$image;
                
                if(!file_exists(IMAGES_PATH.DS.$to['Directory'].DS.$to['NewPath'].DS.$image)){
                    $thumb = PhpThumbFactory::create($image_path);
                    
                    $thumb->adaptiveResize($to['Width'], $to['Height']);
                    $thumb->save(IMAGES_PATH.DS.$to['Directory'].DS.$to['NewPath'].DS.$image, 'PNG');
                }
                $this->updateImages($to);
                
            }catch( Exception $e ) {
                $error=array($e->getFile(), 'Exception: '.$e->getMessage());
                $ExceptionHandler= new Default_Model_ExceptionHandler();
                $ExceptionHandler->saveErrors($error);
            }
        }

/**
 * Método para redimensinar una imagen
 * @param array $to array
 * @return boolean
 */
        public function getImageById($id)
        {

            $TO = new Admin_Model_TO_Settings();
            try{
                $sql=$this->getAdapter()->select()->from(
                            array('i' => TABLE_PREFIX.$this->_name),
                            array('*'))
                    ->where('i.Id=?', $id)
                    ->limit(1);

                $data0 = $this->getAdapter()->fetchAll($sql);
                $rowCount = count($data0);

                if ($rowCount > 0){
                	foreach ($data0 as $dt){
                        $TO->setReal($dt['Real']);
                        $TO->setMiniThumb($dt['Mini_Thumb']);
                        $TO->setThumb($dt['Thumb']);
                        $TO->setMedium($dt['Medium']);
                	}                  
                }
                $data = $TO->getAllVars();
                return $data;
                
            }catch( Exception $e ) {
                $error=array($e->getFile(), 'Exception: '.$e->getMessage());
                $ExceptionHandler= new Default_Model_ExceptionHandler();
                $ExceptionHandler->saveErrors($error);
            }
            return false;
        }


        public function getTotalPictures(){
        	$TO = new Admin_Model_TO_Index();
        	try{
        		$sql=$this->getAdapter()
        					->select()
        						->from(
						        	array('i' => TABLE_PREFIX.$this->_name),
						        	array('Totalpictures' => new Zend_Db_Expr('COUNT(i.Id)'))
        						);
        	
        		$data0 = $this->getAdapter()->fetchAll($sql);
        		$rowCount = count($data0);
        	
        		if ($rowCount > 0){
        			foreach ($data0 as $dt){
        				$TO->setTotalpictures($dt['Totalpictures']);
        			}
        		}
        		$data = $TO->getAllVars();
        		return $data;
        	
        	}catch( Exception $e ) {
        		$error=array($e->getFile(), 'Exception: '.$e->getMessage());
        		$ExceptionHandler= new Default_Model_ExceptionHandler();
        		$ExceptionHandler->saveErrors($error);
        	}
        	return false;
        	
        }


}
